package org.dromara.module.api;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Part;
import org.dromara.common.core.constant.ResponseCode;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.vdurmont.emoji.EmojiParser;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.domain.model.XcxLoginUser;
import org.dromara.common.core.utils.*;
import org.dromara.common.core.utils.file.FileUploadUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.module.domain.AdBanner;
import org.dromara.module.domain.BusinessCooperation;
import org.dromara.module.domain.Parameter;
import org.dromara.module.domain.WxUser;
import org.dromara.module.domain.bo.WxGetPhoneBo;
import org.dromara.module.domain.bo.WxLoginBo;
import org.dromara.module.domain.bo.WxModifyUserBo;
import org.dromara.module.domain.vo.OrderItemArr;
import org.dromara.module.service.*;
import org.dromara.system.domain.SysUser;
import org.dromara.system.service.ISysClientService;
import org.dromara.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.math.BigDecimal;
import java.util.*;

/**
 * 登录相关
 *@Author: ZhouWei
 *@Description:  用户技能相关接口
 *@Date 2025-04-03
 */
@SaIgnore
@Slf4j
@Component
@RestController
@RequestMapping("/api/wxUser")//url:模块/资源/{}/细分
public class UserApiController extends BaseController {

    @Resource
    private IWxUserService userService;
    @Resource
    private IAdBannerService adBannerService;
    @Resource
    private ISysUserService sysUserService;
    @Resource
    private ISysClientService sysClientService;
    @Resource
    private IWxTemplateService wxTemplateService;
    @Resource
    protected RedisTemplate<String, Object> redisTemplate;
    @Resource
    private ParameterService parameterService;
    @Resource
    private IBusinessCooperationService businessCooperationService;

    @Value("${ruoyi.imgUrl}")
    private String imgUrl;//图片地址

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.secret}")
    private String secret;

    @Value("${ruoyi.profile}")
    private String uploadPath;

    /**
     * 微信登录
     * @param
     * @throws Exception
     */
    @PostMapping(value="/wxLogin")
    public R<Map<String ,Object>> Login(@RequestBody WxLoginBo wxLoginBo, HttpServletRequest request) throws Exception{
        Map<String ,Object> map = new HashMap<>();
        try{
            log.info("user/wxLogin 接收的参数： "+wxLoginBo.toString());
            System.out.println("wxLogin 接收的参数： " + wxLoginBo.toString() + "      " +  DateUtils.getTime());
            String code = wxLoginBo.getCode();
            String platform = wxLoginBo.getPlatform();
            double longitude =  StrUtil.isNotEmpty(wxLoginBo.getLng()) ? Double.parseDouble(wxLoginBo.getLng()): 0;
            double latitude = StrUtil.isNotEmpty(wxLoginBo.getLat()) ? Double.parseDouble(wxLoginBo.getLat()): 0;

            String openid = "", unionid = "", sessionkey = "";
            Map<String,Object> mapParam = new HashMap<>();
            if (StrUtil.isEmpty(platform)){
                return R.failApi("登录失败，参数platform不能为空");
            } else if(platform.equals("wxmini")){//普通用户
                mapParam.put("appid",appid);
                mapParam.put("secret", secret);
            } else {
                return R.failApi("登录失败，不支持当前登录方式");
            }
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            mapParam.put("js_code", code);
            mapParam.put("grant_type", "authorization_code");
            String returnParam = HttpUtil.httpClientPost(url, mapParam, "utf-8");
            Gson gson = new Gson();
            Map<String, String> maps = gson.fromJson(returnParam, new TypeToken<Map<String, String>>() {}.getType());
            if(maps != null) {
                openid = maps.containsKey("openid") ? maps.get("openid") : "";
                unionid = maps.containsKey("unionid") ? maps.get("unionid") : "";
                sessionkey =  maps.containsKey("session_key") ? maps.get("session_key") : "";
            } else {
                return R.failApi("系统异常");
            }

            if(!openid.equals("") && !sessionkey.equals("")) {
                String token = UuidUtil.get32UUID();
                QueryWrapper<WxUser> qwUser = new QueryWrapper<>();
                qwUser.eq("open_id",openid);
                qwUser.eq("platform",platform);
                qwUser.last("limit 1");
                WxUser user = userService.getOne(qwUser);
                if(user != null) {//老用户
                    //更新sessionkey
                    user.setSessionKey(sessionkey);
                    if(StrUtil.isEmpty(user.getUnionId())){
                        user.setUnionId(unionid);
                    }
                    user.setLastLoginIp(request.getRemoteAddr());
                    user.setLastActiveTime(new Date());
                    user.setToken(token);
                    user.setLng(new BigDecimal(longitude));
                    user.setLat(new BigDecimal(latitude));
                    user.setPlatform(platform);
                    if(user.getIsAdmin() == null) {
                        user.setIsAdmin(0);
                    }

                    userService.updateLogin(user);
                } else {//新用户
                    user = userService.register(openid, unionid, sessionkey, token, platform, longitude, latitude,null, wxLoginBo.getUserType());
                }
                loginToSys( user, openid);
                map.put("user_id", user.getId());
                map.put("open_id", user.getOpenId());
                map.put("union_id", user.getUnionId());
                map.put("phone_num", user.getPhoneNum());
                map.put("is_admin", user.getIsAdmin() == 1 ? 1 : 0);
                map.put("access_token", StpUtil.getTokenValue());
                map.put("token_timeout", StpUtil.getTokenTimeout());
                map.put("user_type", user.getUserType());
                System.out.println("access_token"+StpUtil.getTokenValue());
                System.out.println("token_timeout"+StpUtil.getTokenTimeout());
                return R.okApi("登录成功",map);
            } else {
                return R.failApi("登录失败");
            }
        } catch (Exception e){
            System.out.println(e.getMessage());
            log.error(e.getMessage(), e);
            e.printStackTrace();
            return R.failApi("系统异常");
        }
    }


    /**
     * 修改昵称头像
     *
     * @param
     * @throws Exception
     */
    @PostMapping(value="/modify/user")
    public R<Void> modifyUser(@RequestBody WxModifyUserBo wxModifyUserBo) throws Exception{
        Map<String ,Object> map = new HashMap<>();
        try{
            log.info("modify/user 接收的参数： "+wxModifyUserBo.toString());
            WxUser wxUser = userService.getById(wxModifyUserBo.getUserId());
            wxUser.setNickName(wxModifyUserBo.getNickName());
            wxUser.setFaceUrl(wxModifyUserBo.getFaceUrl());
            boolean b = userService.updateById(wxUser);
            return toAjaxApi(b);
        } catch (Exception e){
            System.out.println(e.getMessage());
            log.error(e.getMessage(), e);
            e.printStackTrace();
            return R.failApi("系统异常");
        }
    }

    private void loginToSys(WxUser user, String openid){
        XcxLoginUser loginUser = new XcxLoginUser();
        loginUser.setUserId(Long.valueOf(user.getId()));
        loginUser.setUsername(user.getRealName());
        loginUser.setNickname(user.getNickName());
        loginUser.setUserType("xcx");
        loginUser.setOpenid(openid);

        SaLoginModel model = new SaLoginModel();
//        SysClientVo client = sysClientService.queryByClientId("be7052a7e4f802c20df10a8d131adb12");
//        model.setDevice(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
//        model.setTimeout(client.getTimeout());
//        model.setActiveTimeout(client.getActiveTimeout());
//        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);
    }

    /**
     * 绑定手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getWxPhoneNum")
    public R<String> getWxPhoneNum(@RequestBody WxGetPhoneBo wxGetPhoneBo) throws Exception{
        try{
            log.info("user/getWxPhoneNum  接收的参数： "+wxGetPhoneBo.toString());
            Integer userId = wxGetPhoneBo.getUser_id();
            String code = wxGetPhoneBo.getCode();
            String platform = wxGetPhoneBo.getPlatform();
            WxUser user = userService.getById(userId);
            if(user == null){
                return R.failApi("该用户不存在");
            }

            if(StrUtil.isEmpty(code)){
                return R.failApi("code不能为空");
            }

            String accessToken = "";
            //0 - 飞饭吧用户端 小程序  1 - 飞饭吧 商家端 小程序  2 - 飞饭吧 骑手端 小程序
            if(platform.equals("wxmini")){//用户
                accessToken = wxTemplateService.getAccessToken(0);
            }else if(platform.equals("service")){//商户
                accessToken = wxTemplateService.getAccessToken(1);
            }else if(platform.equals("driver")){//配送端
                accessToken = wxTemplateService.getAccessToken(2);
            }else {
                return R.failApi("未识别的平台标识");
            }
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
            Map<String,Object> mapParam = new HashMap<>();
            mapParam.put("code", code);
            String returnParam = OkHttpClientUtil.getInstance().postJson(url, JSONUtil.toJsonStr(mapParam));
            System.out.println("返回信息：" + returnParam);
            JSONObject userJson = JSONUtil.parseObj(returnParam);
            if (userJson.getInt("errcode") == 0) {
                String phone = userJson.getJSONObject("phone_info").getStr("purePhoneNumber");
                int ret = userService.bandPhone(phone, user, platform);
                if (ret > 0) {
                    return R.okApi("绑定成功", phone);
                } else if (ret == -1) {
                    return R.failApi("暂未开通权限，请找客服开通");
                } else {
                    return R.failApi("未绑定成功，请重试");
                }
                //解密成功
            } else {
                return R.failApi("未绑定成功，请重试");
            }
        } catch (Exception e){
            System.out.println(e.getMessage());
            log.error(e.getMessage(), e);
            return R.failApi("系统异常");
        }
    }

    /**
     * 获取用户信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getUserInfoById")
    public JSONObject getUserInfoById(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            log.info("user/getUserInfoById:  "+ requestParam);
            System.out.println("user/getUserInfoById 接受参数：" + requestParam + "      " +  DateUtils.getTime());

            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;


            WxUser user = userService.getById(user_id);
            if(user == null){
                Map<String ,Object> map = new HashMap<>();
                map.put("is_reLogin",0);
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在",map),true,false);
            }

            user.setLastActiveTime(new Date());
            user.setLastLoginIp(request.getRemoteAddr());
            if(StrUtil.isEmpty(user.getToken())){
                user.setToken(UuidUtil.get32UUID());
            }

            if(!user.getPlatform().equals("service")) {//非商户的时候，需要注册账户
                userService.updateLogin(user);
            }
            Map<String ,Object> map = new HashMap<>();
            map.put("is_reLogin",0);

            map.put("user_no",user.getUserNo());
            map.put("user_id",user.getId());
            map.put("is_admin",user.getIsAdmin() == 1 ? 1 : 0);
            map.put("phone_num",user.getPhoneNum());
            map.put("open_id",user.getOpenId());
            map.put("user_type",user.getUserType());

            if(StrUtil.isNotEmpty(user.getFaceUrl())){
                if(!user.getFaceUrl().contains("https")){
                    map.put("face_url", imgUrl + user.getFaceUrl());
                }else{
                    map.put("face_url",  user.getFaceUrl());
                }
            }
            Parameter parameter = parameterService.getParameterById(1);
            map.put("kfPhone", parameter.getMallTelphone());

            map.put("nick_name", "");
            if(StrUtil.isNotEmpty(user.getNickName())){
                map.put("nick_name", EmojiParser.parseToUnicode(user.getNickName()));
            }
            map.put("user_no", user.getUserNo());

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",  map),true,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取用户信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getUserInfo")
    public JSONObject getUserInfo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String encryptedData = jsonRequest.containsKey("encryptedData") ? jsonRequest.getStr("encryptedData") : "";
            String iv = jsonRequest.containsKey("iv") ? jsonRequest.getStr("iv") : "";
            String rawData = jsonRequest.containsKey("rawData") ? jsonRequest.getStr("rawData") : "";
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";

            System.out.println("user/getUserInfo 接受参数：" + requestParam + "      " +  DateUtils.getTime());
            log.info("user/getUserInfo:  "+ requestParam);

            String userInfo = "",unionId = "",nickname = "";
            int gender = 1;
            WxUser user = userService.getById(user_id);
            if(user != null){
                userInfo = AESUtil.decryptWXAppletInfo(encryptedData,user.getSessionKey(),iv);
                JSONObject decodeJSON = null;
                if(userInfo!=null && !userInfo.equals("")){
                    decodeJSON = JSONUtil.parseObj(userInfo);
                    if(JSONUtil.isNull(decodeJSON)){
                        unionId = decodeJSON.containsKey("unionId") ? decodeJSON.getStr("unionId") :"";
                    }
                }
                System.out.println("unionId: " + unionId);
//                String ssss = "";
                JSONObject userInfoJson = null;
                if(!rawData.equals("")){
                    userInfoJson = JSONUtil.parseObj(rawData);
                    if(userInfoJson != null && userInfoJson.size() > 0){
                        if(nickname.equals("")){
                            System.out.println("nickname 处理前: " + nickname);
                            nickname = userInfoJson.containsKey("nickName") ? userInfoJson.getStr("nickName") : user.getNickName();
                            nickname = EmojiParser.parseToAliases(nickname);
                            System.out.println("nickname 处理后: " + nickname);
                        }
                        gender = userInfoJson.containsKey("gender") ? userInfoJson.getInt("gender"):1;
                    }
                }

                user.setSex(gender);
                if(!unionId.equals("")){
                    user.setUnionId(unionId);
                }

//                if(StrUtil.isNotEmpty(user.getUnionId())){
//                    QueryWrapper<UserMp> qw = new QueryWrapper<>();
//                    qw.eq("platform", platform);
//                    qw.eq("union_id",user.getUnionId());
//                    qw.last("limit 1");
//                    UserMp userMp = userMpService.getOne(qw);
//                    if(userMp != null){
//                        if(userMp.getMerId()!=null && (user.getMerId() == null || user.getMerId() == 0)){
//                            user.setMerId(userMp.getMerId());
//                            user.setUserType(1);
//                            user.setIsAdmin(1);
//                        }
//                    }
//                }
//                userService.updateLogin(user);

//                MerUser merUser = merUserService.getMerUser(user.getId());
                Map<String ,Object> map = new HashMap<String, Object>();
                map.put("user_id",user.getId());
                map.put("user_no",user.getUserNo());
                map.put("is_admin",user.getIsAdmin() == 1 ? 1 : 0);
                map.put("is_focus_mp",0);

//                QueryWrapper<UserMp> qw = new QueryWrapper<>();
//                qw.eq("platform", platform);
//                qw.eq("union_id",user.getUnionId());
//                qw.last("limit 1");
//                UserMp userMp = userMpService.getOne(qw);
//                if(userMp!=null){
//                    map.put("is_focus_mp",1);
//                }
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"用户不存在"),true,true);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取用户个人中心的显示数据  包括 优惠券的数量 底部广告，订单类型的数量
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getUserInfoData")
    public JSONObject getUserInfoData(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            //1.获取订单类型的数量  待付款、待发货、已发货、待评价、售后
            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            List<OrderItemArr> list = new ArrayList<>();
            //订单状态订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价
            // 5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货 10  - 已完成
            String[] status = {"全部","待支付","已支付", "已完成","售后"};
            int[] states = {-1, 0, 2, 10 , 8};//3
            for(int i = 0; i < status.length; i++){
                OrderItemArr orderItemArr0 = new OrderItemArr();
                orderItemArr0.setId(states[i]);
                int orderNum = 0;//productOrderService.getOrderCountByState(user_id,states[i]);
                orderItemArr0.setOrderNum(orderNum);
                orderItemArr0.setUrl("/pages/order/productList/index?from_type=0&state=" + states[i] + "&index="+(i));
                orderItemArr0.setOrderStatus(status[i]);
                orderItemArr0.setImgSrc(imgUrl + "simple/image/orderlist" + i +".png");
                list.add(orderItemArr0);
            }
            map.put("orderItemArr",list);

            //3.底部广告
            AdBanner banner = adBannerService.getBannerByAdType(2);
            map.put("banner",banner);
            if(banner != null){
                map.put("hasBanner",1);
            }else{
                map.put("hasBanner",0);
            }

            map.put("user_no",user.getUserNo());

            map.put("phone_num",user.getPhoneNum());
            if(StrUtil.isNotEmpty(user.getFaceUrl())){
                if(!user.getFaceUrl().contains("https")){
                    map.put("face_url", imgUrl + user.getFaceUrl());
                }else{
                    map.put("face_url",  user.getFaceUrl());
                }
            }

            Parameter parameter = parameterService.getParameterById(1);
            if(parameter != null){
                map.put("kfPhone", parameter.getMallTelphone());
            }

            map.put("nick_name", "");
            if(StrUtil.isNotEmpty(user.getNickName())){
                map.put("nick_name", EmojiParser.parseToUnicode(user.getNickName()));
            }

            map.put("phone_num",user.getPhoneNum());

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"获取成功",map),true,false);

        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 搜索用户 根据昵称 手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/searchUser")
    public JSONObject searchUser(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("user/getPhoneNum  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int sys_user_id = jsonRequest.containsKey("sys_user_id") ? jsonRequest.getInt("sys_user_id") : 0;

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.getById(sys_user_id);
            if(sysUser  == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该绑定账号不存在"),true,true);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功"),false,false);
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 搜索用户 根据昵称 手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/getAccountInfo")
    public JSONObject getAccountInfo(@RequestBody String requestParam, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("user/getPhoneNum  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            map.put("phone_num",user.getPhoneNum());
            if(StrUtil.isNotEmpty(user.getFaceUrl())){
                if(!user.getFaceUrl().contains("https")){
                    map.put("face_url", imgUrl + user.getFaceUrl());
                }else{
                    map.put("face_url",  user.getFaceUrl());
                }
            }
            map.put("nick_name", "");
            if(StrUtil.isNotEmpty(user.getNickName())){
                map.put("nick_name", EmojiParser.parseToUnicode(user.getNickName()));
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"查询成功",map),false,false);
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 搜索用户 根据昵称 手机号
     * @param
     * @throws Exception
     */
    @PostMapping(value="/updateNickName")
    public JSONObject updateNickName(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            log.info("user/updateNickName  接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String nickName = jsonRequest.containsKey("nickName") ? jsonRequest.getStr("nickName") : null;

            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }
            user.setNickName(nickName);

            boolean bl = userService.updateById(user);
            if(bl){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"保存成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"保存失败"),true,true);
            }
        } catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            log.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家入驻的图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/updateFaceUrl")
    public JSONObject uploadImgRepair(@RequestParam("user_id") int user_id, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            WxUser user = userService.getById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "用户不存在"), true, true);
            }
            String faceUrl = "";
            Collection<Part> parts = null;
            try {
                parts = request.getParts();
            } catch (ServletException e) {
                throw new RuntimeException(e);
            }
            for (Part part : parts) {
                String partName = part.getName();
                String fileName = part.getSubmittedFileName();

                if (StrUtil.isNotEmpty(part.getName())
                    && StrUtil.isNotEmpty(fileName)
                    && (fileName.contains("jpg") || fileName.contains("jpeg") || fileName.contains("png"))) {

                    // 保存文件，例如写入磁盘
                    String prefix = FileUploadUtils.getUploadPrefix(0);
                    String random = UUID.randomUUID() + "";
                    String imgKey = prefix + DateUtils.getSdfYearDay() + "/" + random + ".jpg";

                    String path = uploadPath + "/" + prefix + DateUtils.getSdfYearDay();
                    File file = new File(path);
                    if (!file.exists() && !file.isDirectory()) {
                        file.mkdirs();
                    }

                    File desc = FileUploadUtils.getAbsoluteFile(path, random + ".jpg");

                    desc = FileUtil.touch(desc);
                    FileUtil.writeFromStream(part.getInputStream(), desc);

                    faceUrl = imgUrl + imgKey;
                    user.setFaceUrl(imgKey);
                    userService.updateById(user);
//                    return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "上传成功",faceUrl), true, false);
                }
            }

            return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "上传成功",faceUrl), true, false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            log.error(e.toString(), e);
            System.out.println(""+e.getMessage());
        }
        return result;
    }


    /**
     * 商务合作 上报
     *
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/business/cooperation")
    public JSONObject businessCooperation(@RequestBody String requestParam) throws Exception {
        JSONObject result = null;
        try {
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String phone_num = jsonRequest.containsKey("phone_num") ? jsonRequest.getStr("phone_num") : "";
            String remark = jsonRequest.containsKey("remark") ? jsonRequest.getStr("remark") : "";
            String real_name = jsonRequest.containsKey("real_name") ? jsonRequest.getStr("real_name") : "";

            BusinessCooperation cooperation = new BusinessCooperation();
            cooperation.setWxUserId(user_id);
            cooperation.setPhone(phone_num);
            cooperation.setRealName(real_name);
            cooperation.setRemark(remark);
            cooperation.setCreateTime(new Date());
            boolean ret = businessCooperationService.save(cooperation);
            if (ret) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "提交成功，我们会尽快联系您"), true, true);
            } else {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "提交成功，请稍后重试"), true, true);
            }
        } catch (Exception e) {
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR, "系统异常", e.getMessage()), true, true);
            log.error(e.toString(), e);
            e.printStackTrace();
        }
        return result;
    }

}
